/* 
 * Xu ly Form voi AJAX 
 * Su dung jQuery Form
 * 
 * author: luubk
 * date: 2012 - 06 - 10
 */


/**
 * This javascript file checks for the brower/browser tab action.
 * It is based on the file menstioned by Daniel Melo.
 * Reference: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
 */
var validNavigation = false;

function wireUpEvents(message) {
    /**
   * For a list of events that triggers onbeforeunload on IE
   * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
   *
   * onbeforeunload for IE and chrome
   * check http://stackoverflow.com/questions/1802930/setting-onbeforeunload-on-body-element-in-chrome-and-ie-using-jquery
   */
    var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
    var leave_message;
    if(message != '')
        leave_message = message;
    else
        leave_message = 'You sure you want to leave?'
    
    function goodbye(e) {
        if (!validNavigation) {
            if (dont_confirm_leave!==1) {
                if(!e) e = window.event;
                //e.cancelBubble is supported by IE - this will kill the bubbling process.
                e.cancelBubble = true;
                e.returnValue = leave_message;
                //e.stopPropagation works in Firefox.
                if (e.stopPropagation) {
                    e.stopPropagation();
                    e.preventDefault();
                }
                //return works for Chrome and Safari
                return leave_message;
            }
        }
    }
    window.onbeforeunload=goodbye;

    // Attach the event keypress to exclude the F5 refresh
    $('document').bind('keypress', function(e) {
        if (e.keyCode == 116){
            validNavigation = true;
        }
    });

    // Attach the event click for all links in the page
    $("a").bind("click", function() {
        validNavigation = true;
    });

    // Attach the event submit for all forms in the page
    $("form").bind("submit", function() {
        validNavigation = true;
    });

    // Attach the event click for all inputs in the page
    $("input[type=submit]").bind("click", function() {
        validNavigation = true;
    });

}



$(document).ready(function() {        
    // show a simple loading indicator	
    $("footer span.loading").ajaxStart(function() {
        $(this).show();
        validNavigation = false;
        wireUpEvents('Một số thao tác vẫn đang thực hiện, bạn vui lòng chờ trong giây lát!');
    }).ajaxStop(function() {
        $(this).hide();
        validNavigation = true;
    }).ajaxError(function(a, b, e) {        
        throw e;                
    });
        
    $('#form').ajaxForm({ 
        dataType:  'json', 
        success:   processJson
    });

    function processJson(json){        
        if(json.message == 'error'){
            data = '<h4 class="alert_error">' + json.data + '<h4>'
        }		
        if(json.message == 'warning'){
            data = '<h4 class="alert_warning">' + json.data + '<h4>'
        }		
        if(json.message == 'success')
            data = '<h4 class="alert_success">' + json.data + '<h4>';
            
        if(json.message == 'custom')            
            data = json.data;                
                
        //        if(json.success == true)            
        //            $('#form').resetForm();
                        
        $("#form_result").html(data);
        window.scrollTo(0,0) ;	
    }
});

function url_title(input, result)
{
    Text = input.value;
    // Xử lý ký tự Unicode
    in_chrs =  'áàảãạăắặằẳẵâấầẩẫậđéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵÁÀẢÃẠĂẮẶẰẲẴÂẤẦẨẪẬĐÉÈẺẼẸÊẾỀỂỄỆÍÌỈĨỊíìỉĩịÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴ',
    out_chrs = 'aaaaaaaaaaaaaaaaadeeeeeeeeeeeooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIiiiiiOOOOOOOOOOOOOOOOOOUUUUUUUUUUUUYYYYY'
    transl = {};
        
    eval('var chars_rgx = /['+in_chrs+']/g');
    for(var i = 0; i < in_chrs.length; i++)
    {
        transl[in_chrs.charAt(i)] = out_chrs.charAt(i); 
    }
    Text = Text.replace(chars_rgx, function(match){
        return transl[match]; 
    });                     
    
    // Bỏ đi các ký tự đặc biệt    
    Text = Text
    .toLowerCase()
    .replace(/ /g,'-')
    .replace(/[^\w-]+/g,'')        
    .replace(/--/g, '-');        
    
    $(result).val(Text);
}

/**
 * Giới hạn chữ cái
 */
function char_limit(area, num, show)
{                
    count = num - area.value.length;
    $(show).html(count);
    new_text = area.value;
    if(count <= 1)
        new_text = area.value.substr(0, num);            
    
    $(area).val(new_text);
            
}
